package cn.b.sky.admin.controller;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.i18n.service.I18nService;
import cn.b.sky.admin.model.BatchJobReport;
import cn.b.sky.admin.model.DWZResult;
import cn.b.sky.admin.model.Factory;
import cn.b.sky.admin.model.FunctionGroup;
import cn.b.sky.admin.model.condition.FactoryCondition;
import cn.b.sky.admin.service.FactoryService;
import cn.b.sky.admin.service.FunctionGroupService;
import cn.b.sky.admin.utils.EncryptAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/management/factory/*")
public class FactoryController extends BaseController {

  private static final String BLANK_MSG = "{}";

  @Autowired
  FactoryService factoryService;

  @Autowired
  FunctionGroupService functionGroupService;

  @Resource
  private I18nService i18nService;
  
  @RequestMapping("pageList")
  public String factoryPage(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    return "admin/factory/factory_list";
  }

  @RequestMapping("getFactories")
  @ResponseBody
  public DWZResult getFactories(FactoryCondition condition) {
    if (null == condition) {
      condition = new FactoryCondition();
    }
    condition.setData(factoryService.selectFactoryListByCondition(condition));
    condition.setTotalCount(factoryService.selectFactoryCountByCondition(condition));
    return ajaxDone(condition);
  }

  @RequestMapping("createFactoryPage")
  public String createFactoryPage(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("groups", functionGroupService.getAllFunctionGroups());
    model.addAttribute("factories", factoryService.selectAllFactories());
    return "admin/factory/create_factory_page";
  }

  @RequestMapping("validateSiteCode")
  @ResponseBody
  public boolean validateSiteCode(String siteCode) {
    if (StringUtils.isBlank(siteCode)) {
      return true;
    } else {
      Factory factory = factoryService.selectFactory(siteCode);
      return null == factory;
    }
  }

  @RequestMapping("saveFactory")
  @ResponseBody
  public DWZResult saveFactory(Factory factory, String password, String[] functionGroupCodes, String sourceSiteCode) {
    try {
      factory.setCreateInfo();
      Set<String> tableSet = getTableSet(functionGroupService.getFunctionGroupsByCodes(functionGroupCodes));
      factoryService.insertTableData(factory, tableSet, sourceSiteCode);
      factoryService.updateAdminPassword(factory.getSiteCode(), EncryptAlgorithm.hexMD5(password));
      //复制完数据进行新工厂国际化数据缓存刷新
      i18nService.flushLocaleResourceBundle(factory.getSiteCode());
      return ajaxDone(true);
    } catch (Exception e) {
      LOGGER.error(BLANK_MSG, e);
      return ajaxError("保存失败，请稍候重试");
    }
  }

  @RequestMapping("updateFactory")
  @ResponseBody
  public DWZResult updateFactory(Factory factory) {
    try {
      factory.setCreateInfo();
      factoryService.updateFactory(factory);
      return ajaxDone(null);
    } catch (Exception e) {
      LOGGER.error(BLANK_MSG, e);
      return ajaxError("保存失败，请稍候重试");
    }
  }

  @RequestMapping("factoryPage")
  public String factoryPage(Model model, String navTabId, String type, String siteCode) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("type", type);
    model.addAttribute("factory", factoryService.selectFactory(siteCode));
    return "admin/factory/factory_page";
  }

  @RequestMapping("deleteFactory")
  @ResponseBody
  public DWZResult deleteFactory(HttpServletRequest request, String siteCodes, String navTabId) {
    if (StringUtils.isBlank(siteCodes)) {
      return ajaxError(SystemConstant.PARAMETERNULL);
    }
    String[] idArr = siteCodes.split(",");
    BatchJobReport[] reports = new BatchJobReport[idArr.length];
    Set<String> tableList = getTableSet(functionGroupService.getAllFunctionGroups());
    int failures = 0;
    for (int i = 0; i < idArr.length; i++) {
      reports[i] = factoryService.deleteFactory(idArr[i], tableList);
      if (!reports[i].isSuccess()) {
        failures += 1;
      }
    }
    if (failures == 0) {
      return navTabAjaxDone(navTabId, null, null, null, "操作成功", null);
    } else {
      return batchjobAjaxDone(request, Arrays.asList(reports));
    }
  };
  
  /**
   * 
   * <strong>Title : getTableSet<br></strong>
   * <strong>Description : </strong>根据功能组获取设计的所有表格<br> 
   * <strong>Create on : 2016年6月14日 上午9:26:40<br></strong>
   * <p>
   * @param functionGroups
   * @return
   * LinkedHashSet<String>
   * @throws 
   * @author Yantao.Lu<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private LinkedHashSet<String> getTableSet(List<FunctionGroup> functionGroups) {
    LinkedHashSet<String> tableSet = new LinkedHashSet<String>();
    for (FunctionGroup functionGroup : functionGroups) {
      for (String tableName : functionGroup.getTableNameList().split(",")) {
        tableSet.add(tableName.trim());
      }
    }
    return tableSet;
  }
}
